package com.lanou3g.ptp.api.resolver;

import com.alibaba.dubbo.config.annotation.Reference;
import com.lanou3g.ptp.api.resolver.annotation.SsoStudent;
import com.lanou3g.ptp.api.resolver.annotation.SsoTeacher;
import com.lanou3g.ptp.entity.Student;
import com.lanou3g.ptp.exception.PermissionDeniedException;
import com.lanou3g.ptp.sso.service.SsoService;
import org.springframework.core.MethodParameter;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.support.WebDataBinderFactory;
import org.springframework.web.context.request.NativeWebRequest;
import org.springframework.web.method.support.HandlerMethodArgumentResolver;
import org.springframework.web.method.support.ModelAndViewContainer;

import javax.servlet.http.HttpServletRequest;
import java.lang.reflect.Parameter;

/**
 * 创建人: 武奇
 * 创建事件: 2019/8/15
 */
public class SsoStudentArgumentResolver implements HandlerMethodArgumentResolver {

    @Reference
    private SsoService ssoService;

    @Override
    public boolean supportsParameter(MethodParameter parameter) {
        return parameter.hasParameterAnnotation(SsoStudent.class)
                && parameter.getParameterType() == Student.class;
    }

    @Override
    public Object resolveArgument(MethodParameter parameter, ModelAndViewContainer mavContainer,
                                  NativeWebRequest webRequest, WebDataBinderFactory binderFactory) throws Exception {
        HttpServletRequest req = webRequest.getNativeRequest(HttpServletRequest.class);
        String token = req.getHeader("token");
        if (!StringUtils.hasText(token)) {
            throw new PermissionDeniedException("请登录");
        }
        Object user = null;
        try {
            user = this.ssoService.tokenUser(token);
        } catch (Exception e) {
            throw new PermissionDeniedException("非法token");
        }
        if (user instanceof Student) {
            return user;
        }
        Parameter[] parameters = parameter.getMethod().getParameters();
        for (Parameter param : parameters) {
            if (param.isAnnotationPresent(SsoTeacher.class)) {
                return null;
            }
        }

        throw new PermissionDeniedException("您可能不是学生");
    }
}
